package com.sskj.gocoin.v.activity;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.gocoin.MyAppLication;
import com.sskj.gocoin.R;
import com.sskj.gocoin.R2;
import com.sskj.gocoin.common.App;
import com.sskj.gocoin.common.Constants;
import com.sskj.gocoin.common.rxbus2.RxBus;
import com.sskj.gocoin.common.widget.ToolBarLayout;
import com.sskj.gocoin.component.DaggerUserDataComponent;
import com.sskj.gocoin.p.activity.PwdResetPresenter;
import com.sskj.gocoin.utils.CheckUtil;
import com.sskj.gocoin.utils.ClickUtil;
import com.sskj.gocoin.utils.DisposUtil;
import com.sskj.gocoin.utils.SPUtils;
import com.sskj.gocoin.utils.StringUtils;
import com.sskj.gocoin.utils.ToastUtil;
import com.sskj.gocoin.v.base.BaseActivity;
import com.sskj.lib.RConfig;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.router.provider.LogoutProvider;
import com.sskj.lib.util.TipUtil;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * <pre>
 *     author : 吕志豪
 *     e-mail : 1030753080@qq.com
 *     time   : 2018/04/02
 *     desc   :密码修改或重置页面，默认为重置页面，修改页面传递Constants.IS_RESET false
 *     version: 1.0
 * </pre>
 */

public class PwdResetActivity extends BaseActivity<PwdResetPresenter> {
    @BindView(R2.id.et_pwd)
    EditText etPwd;
    @BindView(R2.id.iv_toggle_pwd)
    ImageView ivTogglePwd;
    @BindView(R2.id.et_pwd_again)
    EditText etPwdAgain;
    @BindView(R2.id.iv_toggle_pwd_again)
    ImageView ivTogglePwdAgain;

    @BindView(R2.id.etCode)
    EditText etCode;
    @BindView(R2.id.btSendCode)
    TextView btSendCode;
    @BindView(R2.id.tv_phone)
    TextView tvPhone;
    @BindView(R2.id.bt_next_step)
    Button btNextStep;
    @BindView(R2.id.toolBar)
    ToolBarLayout toolBarLayout;
    private boolean isSee = false;
    private boolean isSeeAgain = false;
    private boolean isSeeOrigin = false;
    private String phone;
    private String code;
    private boolean mIsReset;

    @Inject
    UserViewModel userViewModel;
    UserData userData;

    private Disposable disposable;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pws_reset;
    }

    @Override
    public PwdResetPresenter getPresenter() {
        return new PwdResetPresenter();
    }

    @Override
    protected void onViewBinding() {
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            }
        });
        toolBarLayout.setLeftButtonOnClickLinster(v -> finish());
        //true 忘记密码进入 false 安全中心进入
        mIsReset = getIntent().getBooleanExtra(Constants.IS_RESET, true);
        if (mIsReset) {
            phone = getIntent().getStringExtra(Constants.PHONE);
            code = getIntent().getStringExtra(Constants.CODE);
        } else {
            phone = (String) SPUtils.get(MyAppLication.getApplication(), Constants.SP_MOBILE, "");
        }

        String mobile = MyAppLication.getMobile();
        if (!TextUtils.isEmpty(mobile)) {
            if (mobile.contains("@")) {
                tvPhone.setText(App.INSTANCE.getString(R.string.address) + StringUtils.changeText(mobile));
            } else {
                tvPhone.setText(App.INSTANCE.getString(R.string.xmlactivity_personal56) + StringUtils.changeText(mobile));
            }
        }
        ClickUtil.click(btSendCode, () -> { //获取验证码
            if (CheckUtil.isEmail(MyAppLication.getMobile())) {
                mPresenter.sendEmail();
            } else {
                mPresenter.sendCode();
            }


        });


        ClickUtil.click(btNextStep, () -> {
            if (mIsReset) {
                googleCheck();
//                mPresenter.reset(phone, etPwd.getText().toString(), code);
            } else {
                if (TextUtils.isEmpty(etCode.getText().toString())) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.fabimineJavaBindEmailActivity5));
                    return;
                }
                if (TextUtils.isEmpty(etPwd.getText().toString())) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.xmlactivity_pws_reset88));
                    return;
                }
                if (!com.sskj.common.util.CheckUtil.isPassWord(etPwd.getText().toString())) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strPwdResetActivity203));
                    return;
                }
                if (TextUtils.isEmpty(etPwdAgain.getText().toString())) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.xmlactivity_pws_reset78));
                    return;
                }
                if (!etPwd.getText().toString().equals(etPwdAgain.getText().toString())) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.strPwdResetActivity666));
                    return;
                }
                googleCheck();
//                    mPresenter.resetWithOrigin(etPwdOrigin.getText().toString(), etPwd.getText().toString());
                }
        });

        ClickUtil.click(200, ivTogglePwdAgain, () -> {
            if (isSeeAgain) {
                isSeeAgain = false;
                etPwdAgain.setTransformationMethod(PasswordTransformationMethod.getInstance());
                ivTogglePwdAgain.setImageResource(R.mipmap.unsee);
            } else {
                isSeeAgain = true;
                etPwdAgain.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                ivTogglePwdAgain.setImageResource(R.mipmap.see);
            }
        });
        ClickUtil.click(200, ivTogglePwd, () -> {
            if (isSee) {
                isSee = false;
                etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                ivTogglePwd.setImageResource(R.mipmap.unsee);
            } else {
                isSee = true;
                etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                ivTogglePwd.setImageResource(R.mipmap.see);
            }
        });
    }

    public void resetSuccess() {
        finish();
        if (!mIsReset) {
//            logout();
            LogoutProvider logoutProvider = ARouter.getInstance().navigation(LogoutProvider.class);
            logoutProvider.logout();
        } else {
            ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
    }
    /**
     * 谷歌验证
     */
    private void googleCheck() {
      //  if (userData.getConfig().getGoogle_verify() == 1) {
        if (false) {
            TipUtil.googleCheckTip(this, (pwd) -> {
                mPresenter.requestGoogleCheck(pwd);
            });
        } else {
            //关闭之后不作处理
            if (mIsReset) {
                mPresenter.reset(phone, etPwd.getText().toString(), code);
            } else {
                mPresenter.resetWithOrigin( etPwd.getText().toString(),etCode.getText().toString());
            }
        }
    }

    public void sendCodeOk() {
        DisposUtil.close(disposable);
        disposable = Flowable.intervalRange(1, 60, 0, 1, TimeUnit.SECONDS)
                .map(i -> 60 - i)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(i -> {
                    btSendCode.setText(String.format(App.INSTANCE.getString(R.string.strRegisterActivity9), i));
                }, System.out::println, () -> {
                    btSendCode.setEnabled(true);
                    btSendCode.setText(getString(R.string.xmlactivity_register74));

                });

    }

    public void sendCodeError() {
        btSendCode.setEnabled(true);
    }


    /**
     * 谷歌验证通过
     */
    public void googleCheckSuccess() {
        if (mIsReset) {
            mPresenter.reset(phone, etPwd.getText().toString(), code);
        } else {
            mPresenter.resetWithOrigin(etPwd.getText().toString(),etCode.getText().toString());
        }
    }

}
